package com.binc.testspring.study.design.iterator;

import lombok.Builder;
import lombok.Data;
import lombok.ToString;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;

/**
 * FileName: TestIterator  玩玩迭代器模式
 *
 *     1. 抽象一个迭代器接口
 *     2. 抽象一个容器
 *     3. 具体的迭代器类
 *     4 具体的容器类
 *
 *
 * Autho: binC
 * Date:  2022/3/31 10:39
 */
public class TestIterator {
    public static void main(String[] args) {

        BincUser b1 = new BincUser(1,"Binc一号");
        BincUser b2 = new BincUser(12,"Binc二号");
        BincUser b3 = new BincUser(123,"Binc3号");

        ConcreteAggregate concreteAggregate = new ConcreteAggregate();
        //具体容器的添加
        concreteAggregate.add(b1);
        concreteAggregate.add(b2);
        concreteAggregate.add(b3);

        //容器的遍历
        Interator interator = concreteAggregate.interator();
        while (interator.hasNext()) {
            BincUser next = (BincUser) interator.next();
            System.out.println("====遍历结果"+next.toString());

        }


    }

}

//1 抽象迭代器接口，我们的迭代器就先定义两个方法
// 如果直接用jdk的 Iterator其实更方便
interface  Interator{
    boolean hasNext();
    Object next();
}

//3 具体迭代器
class ConcreteIterator implements  Interator{
    private Vector vector = new Vector(); //定义一个容器
    private int cursor = 0 ;// 定义一个游标

    //构造函数，通过构造函数将具体迭代器的容器完成赋值
    public ConcreteIterator(Vector _vector) {
        this.vector = _vector;
    }

    @Override
    public boolean hasNext() {
        if (this.cursor >= vector.size() ) {
            return false;
        }else {
            return true;
        }
    }

    @Override
    public Object next() {
        Object result = null;
        if (this.hasNext()) {
            result = this.vector.get(this.cursor++);
        } else {
            result = null;
        }
        return result;
    }
}


// 2 抽象容器
interface Aggregate{
    //增加元素
    void add(Object obj);
    // 返回我们自定义的迭代器，然后用得得带起进行遍历
    Interator interator();
}

// 4 具体的容器
class ConcreteAggregate implements Aggregate{
    private Vector vector = new Vector();

    @Override
    public void add(Object obj) {
        this.vector.add(obj);
    }

    @Override
    public Interator interator() {
        return new ConcreteIterator(this.vector);
    }
}

// 5 javabean
@Data
@ToString
@Builder
class BincUser {
    private int age;
    private String name;


}


